import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class TestKeepAlive extends StatefulWidget {
  const TestKeepAlive({super.key});

  @override
  State<TestKeepAlive> createState() => _TestKeepAliveState();
}

class _TestKeepAliveState extends State<TestKeepAlive> {
  @override
  Widget build(BuildContext context) {
    var children = <Widget>[];
    for (int i = 0; i < 6; ++i) {
      //只需要用 KeepAliveWrapper 包装一下即可
      children.add(KeepAliveWrapper(child: Page(title: '$i')));
    }
    return PageView(
      scrollDirection: Axis.vertical,
      allowImplicitScrolling: true,
      children: children,
    );
  }
}

class Page extends StatefulWidget {
  Page({super.key, required this.title});

  late String title;

  @override
  State<Page> createState() => _PageState();
}

class _PageState extends State<Page> {
  @override
  Widget build(BuildContext context) {
    print("创建${widget.title}");
    return Container(
      width: double.infinity,
      height: double.infinity,
      alignment: Alignment.center,
      child: Text(
        widget.title,
        style: TextStyle(fontSize: 50, color: Colors.black),
      ),
    );
  }
}

/// 以下为保活
class KeepAliveWrapper extends StatefulWidget {
  const KeepAliveWrapper({
    Key? key,
    this.keepAlive = true,
    required this.child,
  }) : super(key: key);
  final bool keepAlive;
  final Widget child;

  @override
  _KeepAliveWrapperState createState() => _KeepAliveWrapperState();
}

class _KeepAliveWrapperState extends State<KeepAliveWrapper>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return widget.child;
  }

  @override
  void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
    if (oldWidget.keepAlive != widget.keepAlive) {
      // keepAlive 状态需要更新，实现在 AutomaticKeepAliveClientMixin 中
      updateKeepAlive();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  bool get wantKeepAlive => widget.keepAlive;
}
